package com.dimenlink.web.controller;

import java.util.HashMap;
import java.util.Map;

import com.dimenlink.component.RedisComponent;
import com.dimenlink.entity.constants.Constants;
import com.dimenlink.entity.dto.TokenUserInfoDto;
import com.dimenlink.entity.vo.ResponseVO;
import com.dimenlink.exception.BusinessException;
import com.dimenlink.service.UserInfoService;
import com.dimenlink.utils.StringTools;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

/**
 * 用户信息 Controller
 */
@Slf4j
@RestController
@RequestMapping("/account")
@Validated
public class AccountController extends ABaseController{

	@Resource
	private UserInfoService userInfoService;

	@Resource
	private RedisComponent redisComponent;

	@RequestMapping("/checkCode")
	public ResponseVO checkCode(){
		// 创建验证码
		ArithmeticCaptcha captcha = new ArithmeticCaptcha(100, 42);
		// 获取运算结果
		String code = captcha.text();
		// 保存验证码,并获取key
		String checkCodeKey = redisComponent.saveCheckCode(code);
		// 转换为base64
		String checkCodeBase64 = captcha.toBase64();

		Map<String, String> result = new HashMap<>();
		// 返回结果
		result.put("checkCodeBase64", checkCodeBase64);
		result.put("checkCodeKey", checkCodeKey);
		log.info(result.toString());
		return getSuccessResponseVO(result);
	}

	@RequestMapping("/register")
	public ResponseVO register(@NotEmpty @Email @Size(max = 150) String email,
							   @NotEmpty @Size(max = 20) String nickName,
							   @NotEmpty @Pattern(regexp = Constants.REGEX_PASSWORD) String registerPassword,
							   @NotEmpty String checkCodeKey,
							   @NotEmpty String checkCode){
		try{
			if(!checkCode.equals(redisComponent.getCheckCode(checkCodeKey))){
				throw new BusinessException("图片验证码错误");
			}
			userInfoService.register(email, nickName, registerPassword);
			return getSuccessResponseVO("注册成功！");
		}finally {
			redisComponent.cleanCheckCode(checkCodeKey);
		}
	}

	@RequestMapping("/login")
	public ResponseVO login(HttpServletRequest request,
							HttpServletResponse response,
							@NotEmpty @Email String email,
							@NotEmpty String password,
							@NotEmpty String checkCodeKey,
							@NotEmpty String checkCode){
		try{
			if(!checkCode.equals(redisComponent.getCheckCode(checkCodeKey))){
				throw new BusinessException("图片验证码错误");
			}

			String ip = getIpAddr();
			TokenUserInfoDto tokenUserInfoDto = userInfoService.login(email, password, ip);
			saveToken2Cookie(response, tokenUserInfoDto.getToken());
			//TODO 设置粉丝数、关注数

			return getSuccessResponseVO(null);
		}finally {
			redisComponent.cleanCheckCode(checkCodeKey);

			Cookie[] cookies = request.getCookies();
			String token = null;
			if(cookies != null){
				for(Cookie cookie : cookies){
					if(cookie.getName().equals(Constants.TOKEN_WEB)){
						token = cookie.getValue();
					}
				}
				if(!StringTools.isEmpty(token)){
					redisComponent.cleanToken(token);
				}
			}
		}
	}

	@RequestMapping("/autoLogin")
	public ResponseVO autoLogin(HttpServletResponse response){
		TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto();
		if(tokenUserInfoDto == null){
			return getServerErrorResponseVO(null);
		}
		if(tokenUserInfoDto.getExpireAt() - System.currentTimeMillis()< Constants.REDIS_KEY_EXPIRE_ONE_DAY){
			redisComponent.saveTokenInfo(tokenUserInfoDto);
			saveToken2Cookie(response, tokenUserInfoDto.getToken());
		}
		//TODO 获取粉丝数、关注数,硬币数
		return getSuccessResponseVO(tokenUserInfoDto);
	}

	@RequestMapping("/logout")
	public ResponseVO logout(HttpServletResponse response){
		cleanCookie( response);
		return getSuccessResponseVO(null);
	}
}